package com.snail.service.impl;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.snail.exception.BusinessException;
import com.snail.exception.ErrorCode;
import com.snail.mapper.*;
import com.snail.model.dto.*;
import com.snail.model.pojo.*;
import com.snail.model.vo.SysTeamPageListVo;
import com.snail.response.BaseResponse;
import com.snail.response.PageResponse;
import com.snail.response.ResultUtils;
import com.snail.service.SysTeamService;
import com.snail.service.SysTeamSubscriptionService;
import com.snail.service.SysTeamUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;


/**
 * @author Monica
 * @description 针对表【sys_team(战队信息表)】的数据库操作Service实现
 * @createDate 2025-07-23 14:30:24
 */
@Service
@Slf4j
public class SysTeamServiceImpl extends ServiceImpl<SysTeamMapper, SysTeam> implements SysTeamService {
    @Autowired
    private SysTeamUserService sysTeamUserService;

    @Autowired
    private SysTeamSubscriptionService sysTeamSubscriptionService;

    @Autowired
    private SysTeamSubscriptionMapper sysTeamSubscriptionMapper;

    @Autowired
    private SysTeamUserMapper sysTeamUserMapper;

    @Autowired
    private SysTeamMapper sysTeamMapper;

    @Autowired
    private SysTagMapper sysTagMapper;

    @Autowired
    private SysUserMapper sysUserMapper;

    /**
     * 查询自己创建的战队信息
     */
    @Override
    public List<SysTeam> findCreateTeam(Long userId) {
        LambdaQueryWrapper<SysTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeam::getCreatorId, userId);
        return this.list(queryWrapper);
    }

    /**
     * 查询身为队长的战队信息
     */
    @Override
    public List<SysTeam> selectMyTeams(Long userId) {
        // 1. 查询用户作为队长的 team_id 列表
        LambdaQueryWrapper<SysTeamUser> teamUserQuery = new LambdaQueryWrapper<>();
        teamUserQuery.select(SysTeamUser::getTeamId)
                .eq(SysTeamUser::getUserId, userId)
                .eq(SysTeamUser::getRole, 1); // 角色1=队长

        List<Long> teamIds = sysTeamUserService.list(teamUserQuery)
                .stream()
                .map(SysTeamUser::getTeamId)
                .collect(Collectors.toList());

        // 判断是否有队长的战队信息
        if (teamIds.isEmpty()) {
            return Collections.emptyList();
        }

        // 2. 批量查询战队详情
        return this.lambdaQuery()
                .in(SysTeam::getId, teamIds)
                .list();

    }

    /**
     * 查询自己加入的战队信息通过userId
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysTeam> selectJoinedTeams(Long userId) {
        LambdaQueryWrapper<SysTeamUser> queryWrapper = new LambdaQueryWrapper<>();
        // 查询出成员状态正常且用户id为当前登录用户的战队信息
        queryWrapper.eq(SysTeamUser::getUserId, userId)
                .eq(SysTeamUser::getRole, 0)
                .eq(SysTeamUser::getStatus, 0); // 角色0=成员, 状态0=正常
        List<SysTeamUser> teamUsers = sysTeamUserService.list(queryWrapper);
        // 如果查找出来的战队列表信息不是空
        if (teamUsers != null && !teamUsers.isEmpty()) {
            List<Long> teamIds = teamUsers.stream().map(SysTeamUser::getTeamId).distinct().collect(Collectors.toList());
            // 然后通过查询出来的teamIds去查询战队信息 并排除自己创建的战队信息
            List<SysTeam> joinTeams = this.lambdaQuery().in(SysTeam::getId, teamIds).ne(SysTeam::getCreatorId, userId).list();
            return joinTeams;
        }
        // 如果查找出来的战队列表信息为空，则返回空列表
        return Collections.emptyList();
    }


    /**
     * 查询自己所订阅的全部战队信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public List<SysTeam> selectSubscribeTeams(Long userId) {
        LambdaQueryWrapper<SysTeamSubscription> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeamSubscription::getUserId, userId)
                .eq(SysTeamSubscription::getStatus, 1);
        // 查询出订阅状态正常的战队信息
        List<SysTeamSubscription> teamSubscriptions = sysTeamSubscriptionService.list(queryWrapper);
        // 如果查找出来的战队列表信息不是空
        if (teamSubscriptions != null && !teamSubscriptions.isEmpty()) {
            List<Long> teamIds = teamSubscriptions.stream().map(SysTeamSubscription::getTeamId).distinct().collect(Collectors.toList());
            // 然后通过查询出来的teamIds去查询战队信息并排除自己创建的战队信息
            List<SysTeam> subscribeTeams = this.lambdaQuery().in(SysTeam::getId, teamIds)
                    .ne(SysTeam::getCreatorId, userId).list();
            return subscribeTeams;
        }
        // 如果查找出来的战队列表信息为空，则返回空列表
        return Collections.emptyList();
    }

    /**
     * 根据战队id查询战队详情信息
     */
    @Override
    public TeamDetailsDTO getTeamDetails(Long teamId) {
        // 1. 查询战队基本信息
        SysTeam team = this.lambdaQuery().eq(SysTeam::getId, teamId).one();

        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "战队不存在或已被删除");
        }
        // 2. 构建DTO对象
        TeamDetailsDTO dto = new TeamDetailsDTO();
        // 使用BeanUtils避免手动set（确保字段名一致）
        BeanUtils.copyProperties(team, dto);

        return dto;
    }

    /**
     * 根据战队id查询战队成员信息
     */
    @Override
    public List<TeamMembersDTO> selectTeamMembers(Long teamId) {

        // 利用mapper查询出战队成员信息集合
        List<TeamMembersDTO> teamMembers = sysTeamUserMapper.selectMembersWithUserInfo(teamId);

        return teamMembers;
    }

    /**
     * 订阅战队的请求
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean createSubscription(Long userId, Long teamId, SubscriptionRequestDTO subscriptionRequestDTO) {
        // 检查用户是否该战队
        SysTeam teamExist = this.getById(teamId);
        if (teamExist == null || teamExist.getDeleted() == 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "战队不存在或已被删除");
        }
        // 检查用户是否已经订阅过该战队
        Integer isSubscribe = teamExist.getIsSubscribe();
        if (isSubscribe != 1) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "该战队不需要订阅");
        }
        // 检查是否已有有效订阅
        LambdaQueryWrapper<SysTeamSubscription> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeamSubscription::getUserId, userId).eq(SysTeamSubscription::getTeamId, teamId).in(SysTeamSubscription::getStatus, 0, 1);
        long count = sysTeamSubscriptionService.count(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "您已有待支付或生效中的订阅");
        }
        // 开始处理订阅请求
        SysTeamSubscription subscription = new SysTeamSubscription();
        subscription.setTeamId(teamId);
        subscription.setUserId(userId);
        subscription.setOrderId(subscriptionRequestDTO.getOrderId());
        subscription.setStatus(0); // 初始状态为待支付
        subscription.setAutoRenew(subscriptionRequestDTO.getAutoRenew() ? 1 : 0);

        return sysTeamSubscriptionService.save(subscription);
    }

    /**
     * 取消订阅战队的请求
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteSubscription(Long userId, Long teamId) {
        // 1. 检查战队是否存在
        SysTeam team = this.getById(teamId);
        if (team == null || team.getDeleted() == 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "战队不存在或已被删除");
        }

        // 2. 检查用户是否订阅了该战队（仅查询生效中或待支付的订阅）
        LambdaQueryWrapper<SysTeamSubscription> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeamSubscription::getUserId, userId).eq(SysTeamSubscription::getTeamId, teamId).in(SysTeamSubscription::getStatus, 0, 1); // 0:待支付, 1:生效中

        SysTeamSubscription subscription = sysTeamSubscriptionService.getOne(queryWrapper);
        if (subscription == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "未找到有效订阅记录");
        }

        // 3. 执行取消操作（软删除或更新状态）
        boolean success;
        if (subscription.getStatus() == 0) {
            // 待支付的订阅直接删除
            success = sysTeamSubscriptionService.removeById(subscription.getId());
        } else {
            // 生效中的订阅改为 "已取消" 状态
            subscription.setStatus(2);
            subscription.setUpdateTime(LocalDateTime.now());
            success = sysTeamSubscriptionService.updateById(subscription);
        }
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "取消订阅失败");
        }

        return true;
    }

    /**
     * 退出战队的请求
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean quitTeam(Long userId, Long teamId) {
        // 1. 校验战队是否存在且有效
        SysTeam team = this.getById(teamId);
        if (team == null || team.getDeleted() == 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "战队不存在或已被解散");
        }
        // 2. 校验用户是否在该战队中
        LambdaQueryWrapper<SysTeamUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeamUser::getUserId, userId).eq(SysTeamUser::getTeamId, teamId).eq(SysTeamUser::getStatus, 0);
        SysTeamUser teamUser = sysTeamUserService.getOne(queryWrapper);
        if (teamUser == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "您不在该战队中");
        }
        // 3. 处理退出请求
        if (teamUser.getRole() == 1) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "请先转让队长身份再退出");
        }
        // 普通成员直接退出
        teamUser.setStatus(3);// 状态3=退出
        return sysTeamUserService.updateById(teamUser);
    }

    /**
     * 转让战队的队长
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean transferTeamLeader(Long teamId, Long userId, Long newLeaderId) {
        // 校验战队是否存在且有效
        SysTeam team = this.getById(teamId);
        if (team == null || team.getDeleted() == 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "战队不存在或已被解散");
        }
        // 校验当前用户是不是战队队长
        LambdaQueryWrapper<SysTeamUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeamUser::getUserId, userId).eq(SysTeamUser::getTeamId, teamId).eq(SysTeamUser::getRole, 1);
        SysTeamUser oldLeader = sysTeamUserService.getOne(queryWrapper);
        if (oldLeader == null) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "您不是该战队的队长,没有权限转让");
        }
        // 校验新队长是否存在且有效
        if (userId.equals(newLeaderId)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "不能转让给自己");
        }
        SysTeamUser newLeader = sysTeamUserService.lambdaQuery().eq(SysTeamUser::getUserId, newLeaderId).eq(SysTeamUser::getTeamId, teamId).eq(SysTeamUser::getRole, 0) // 新队长不能已经是队长
                .one();
        if (newLeader == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "目标用户不在战队中或已是队长");
        }

        // 转让队长
        oldLeader.setRole(0);
        newLeader.setRole(1);
        // 更新队长信息
        boolean success = sysTeamUserService.updateBatchById(Arrays.asList(oldLeader, newLeader));
        if (!success) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "转让队长失败");
        }
        log.info("战队队长转让成功：teamId={}, 原队长={}, 新队长={}", teamId, userId, newLeaderId);
        return true;
    }

    /**
     * 修改战队详情的基本信息
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean updateTeamDetails(Long teamId, TeamDetailsDTO teamDetailsDTO, Long userId) {
        // 校验战队是否存在且有效
        SysTeam team = this.getById(teamId);
        if (team == null || team.getDeleted() == 1) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "战队不存在或已被解散");
        }
        // 校验当前用户是不是战队队长
        LambdaQueryWrapper<SysTeamUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeamUser::getUserId, userId).eq(SysTeamUser::getTeamId, teamId).eq(SysTeamUser::getRole, 1);
        SysTeamUser captain = sysTeamUserService.getOne(queryWrapper);
        if (captain == null) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "您不是该战队的队长,没有权限修改");
        }
        //获取当前表里面的最大成员数
        Long countNumbers = sysTeamUserService.lambdaQuery().eq(SysTeamUser::getTeamId, teamId).eq(SysTeamUser::getStatus, 0).count();

        //  数据校验（如最大成员数）
        if (teamDetailsDTO.getMaxCount() != null && teamDetailsDTO.getMaxCount() < countNumbers) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "最大成员数不能小于当前人数");
        }
        //  更新战队信息
        BeanUtils.copyProperties(teamDetailsDTO, team);
        return this.updateById(team);
    }

    /**
     * 移除战队成员
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean removeTeamMember(Long teamId, Long memberId) {
        // 获取当前登录用户
        Long userId = StpUtil.getLoginIdAsLong();
        // 校验当前用户是不是战队队长
        LambdaQueryWrapper<SysTeamUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeamUser::getUserId, userId).eq(SysTeamUser::getTeamId, teamId).eq(SysTeamUser::getRole, 1);
        SysTeamUser captain = sysTeamUserService.getOne(queryWrapper);
        if (captain == null) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "您不是该战队的队长,没有权限移除成员");
        }
        // 校验被移除的成员是否在战队中
        LambdaQueryWrapper<SysTeamUser> memberQueryWrapper = new LambdaQueryWrapper<>();
        memberQueryWrapper.eq(SysTeamUser::getTeamId, teamId).eq(SysTeamUser::getUserId, memberId).eq(SysTeamUser::getStatus, 0);
        SysTeamUser member = sysTeamUserService.getOne(memberQueryWrapper);
        if (member == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "成员不存在或已退出战队");
        }
        // 移除成员
        boolean result = sysTeamUserService.update(new LambdaUpdateWrapper<SysTeamUser>().eq(SysTeamUser::getTeamId, teamId).eq(SysTeamUser::getUserId, memberId).set(SysTeamUser::getStatus, 3));
        return result;
    }

    /**
     * 审核战队成员
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean reviewMember(Long teamId, Long memberId, Integer status, Long userId) {
        // 校验当前用户是不是战队队长
        LambdaQueryWrapper<SysTeamUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeamUser::getUserId, userId)
                .eq(SysTeamUser::getTeamId, teamId)
                .eq(SysTeamUser::getRole, 1);
        SysTeamUser captain = sysTeamUserService.getOne(queryWrapper);
        if (captain == null) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "您不是该战队的队长,没有权限审核成员");
        }
        // 校验被审核的成员是否在战队中
        LambdaQueryWrapper<SysTeamUser> memberQueryWrapper = new LambdaQueryWrapper<>();
        memberQueryWrapper.eq(SysTeamUser::getTeamId, teamId)
                .eq(SysTeamUser::getUserId, memberId)
                .eq(SysTeamUser::getStatus, 1);  // 1 待审核
        SysTeamUser member = sysTeamUserService.getOne(memberQueryWrapper);
        if (member == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "该成员未申请加入战队");
        }

        // 审核成员
        member.setStatus(status);
        member.setAuditorId(userId);
        member.setAuditTime(new Date());
        boolean result = sysTeamUserService.updateById(member);
        if (result) {
            log.info("审核成员成功：teamId={}, memberId={}, status={}", teamId, memberId, status);
        }
        return result;
    }

    /**
     * 获取待审核的成员列表
     */
    @Override
    public List<TeamMembersDTO> getReviewMembers(Long teamId, Long userId) {
        // 校验当前用户是不是战队队长
        LambdaQueryWrapper<SysTeamUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeamUser::getUserId, userId)
                .eq(SysTeamUser::getTeamId, teamId)
                .eq(SysTeamUser::getRole, 1);
        SysTeamUser captain = sysTeamUserService.getOne(queryWrapper);
        if (captain == null) {
            throw new BusinessException(ErrorCode.FORBIDDEN_ERROR, "您不是该战队的队长,没有权限获取待审核成员列表");
        }
        // 查询待审核的成员列表
        List<TeamMembersDTO> teamMembers = sysTeamUserMapper.selectReviewMembers(teamId);
        return teamMembers;
    }

    @Override
    public List<SysTeam> selectMyAllTeams(Long userId) {
        Set<Long> teamIds = new HashSet<>();
        List<SysTeam> allTeams = new ArrayList<>();

        // 添加创建的战队
        List<SysTeam> createTeams = sysTeamMapper.selectList(new LambdaQueryWrapper<SysTeam>().eq(SysTeam::getCreatorId, userId));
        allTeams.addAll(createTeams);
        createTeams.forEach(team -> teamIds.add(team.getId()));
        //获取当前加入的战队，添加到集合中
        List<SysTeamUser> teamUserList = sysTeamUserMapper.selectList(new LambdaQueryWrapper<SysTeamUser>().eq(SysTeamUser::getUserId, userId).eq(SysTeamUser::getStatus, 0));
        teamUserList.forEach(teamUser -> {
            SysTeam team = sysTeamMapper.selectById(teamUser.getTeamId());
            if (team != null) {
                allTeams.add(team);
                teamIds.add(team.getId());
            }
        });


        // 添加订阅的战队
        List<SysTeamSubscription> subscriptionList = sysTeamSubscriptionMapper.selectList(
                new LambdaQueryWrapper<SysTeamSubscription>().eq(SysTeamSubscription::getUserId, userId));
        subscriptionList.stream()
                .map(SysTeamSubscription::getTeamId)
                .filter(teamId -> !teamIds.contains(teamId))
                .forEach(teamId -> {
                    SysTeam team = sysTeamMapper.selectById(teamId);
                    if (team != null) {
                        allTeams.add(team);
                        teamIds.add(teamId);
                    }
                });
        allTeams.forEach(team -> {
            team.setTag(analyzeTags(team.getTag(), 1));
            team.setUsername(sysUserMapper.selectById(team.getCreatorId()).getUsername());
        });
        return allTeams;
    }

    /**
     * 获取带有队长信息的战队列表
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public PageResponse<SysTeamWithCaptainDTO> getTeamListWithCaptain(SysTeamPageListVo sysTeamPageListVo) {
        // 1. 构建分页查询
        Page<SysTeam> teamPage = new Page<>(sysTeamPageListVo.getCurrent(), sysTeamPageListVo.getPageSize());
        LambdaQueryWrapper<SysTeam> queryWrapper = new LambdaQueryWrapper<>();

        // 2. 设置查询条件
        if (StringUtils.hasLength(sysTeamPageListVo.getTeamName())) {
            queryWrapper.like(SysTeam::getTeamName, sysTeamPageListVo.getTeamName());
        }
        if (sysTeamPageListVo.getNeedReview() != null) {
            queryWrapper.eq(SysTeam::getNeedReview, sysTeamPageListVo.getNeedReview());
        }

        // 3. 执行分页查询
        Page<SysTeam> pageList = sysTeamMapper.selectPage(teamPage, queryWrapper);

        // 4. 转换为DTO并补充队长信息
        List<SysTeamWithCaptainDTO> dtoList = pageList.getRecords().stream().map(team -> {
            SysTeamWithCaptainDTO dto = new SysTeamWithCaptainDTO();
            BeanUtils.copyProperties(team, dto);

            // 4.1 只获取队长信息（role=1）
            SysTeamUser captain = sysTeamUserMapper.selectOne(
                    new LambdaQueryWrapper<SysTeamUser>()
                            .eq(SysTeamUser::getTeamId, team.getId())
                            .eq(SysTeamUser::getRole, 1)
                            .last("LIMIT 1")
            );

            if (captain != null) {
                SysUser captainUser = sysUserMapper.selectById(captain.getUserId());
                if (captainUser != null) {
                    dto.setUsername(captainUser.getUsername()); // 队长用户名
                    dto.setRole(captain.getRole());            // 队长角色
                }
            }

            return dto;
        }).collect(Collectors.toList());

        // 5. 构建返回的分页结果
        Page<SysTeamWithCaptainDTO> resultPage = new Page<>(
                pageList.getCurrent(),
                pageList.getSize(),
                pageList.getTotal()
        );
        resultPage.setRecords(dtoList);

        return ResultUtils.pageSuccess(resultPage);
    }

    /**
     * 获取战队人数
     */
    @Override
    public Page<TeamWithMemberCountDTO> getTeamListWithRealMemberCount(TeamQueryDTO queryDTO) {
        // 1. 先查询战队基本信息
        Page<SysTeam> teamPage = lambdaQuery()
                .eq(SysTeam::getDeleted, 0)
                .like(StringUtils.hasLength(queryDTO.getTeamName()), SysTeam::getTeamName, queryDTO.getTeamName())
                .eq(queryDTO.getNeedReview() != null, SysTeam::getNeedReview, queryDTO.getNeedReview())
                .page(new Page<>(queryDTO.getCurrent(), queryDTO.getPageSize()));

        if (teamPage.getRecords().isEmpty()) {
            return new Page<>(queryDTO.getCurrent(), queryDTO.getPageSize(), 0);
        }

        // 2. 方法统计每个战队的成员数
        List<TeamWithMemberCountDTO> resultList = teamPage.getRecords().stream()
                .map(team -> {
                    // 调用你的现有方法获取成员列表
                    List<TeamMembersDTO> members = sysTeamUserMapper.selectMembersWithUserInfo(team.getId());

                    // 构建返回DTO
                    return TeamWithMemberCountDTO.builder()
                            .id(team.getId())
                            .teamName(team.getTeamName())
                            .description(team.getDescription())
                            .logo(team.getLogo())
                            .tag(team.getTag())
                            .maxCount(team.getMaxCount())
                            .needReview(team.getNeedReview())
                            .captainName(team.getCreatorId().toString())
                            .currentCount(members.size())
                            .build();
                })
                .collect(Collectors.toList());

        // 3. 构建分页结果
        Page<TeamWithMemberCountDTO> resultPage = new Page<>();
        resultPage.setRecords(resultList);
        resultPage.setTotal(teamPage.getTotal());
        resultPage.setCurrent(teamPage.getCurrent());
        resultPage.setSize(teamPage.getSize());

        return resultPage;
    }


    /**
     * 获取战队列表
     */
    @Override
    public PageResponse<SysTeam> getTeamList(SysTeamPageListVo sysTeamPageListVo) {
        Page<SysTeam> teamPage = new Page<>(sysTeamPageListVo.getCurrent(), sysTeamPageListVo.getPageSize());
        LambdaQueryWrapper<SysTeam> queryWrapper = new LambdaQueryWrapper<>();
        if (StringUtils.hasLength(sysTeamPageListVo.getTeamName())) {
            queryWrapper.like(SysTeam::getTeamName, sysTeamPageListVo.getTeamName());
        }
        if (sysTeamPageListVo.getNeedReview() != null) {
            queryWrapper.eq(SysTeam::getNeedReview, sysTeamPageListVo.getNeedReview());
        }
        Page<SysTeam> pageList = sysTeamMapper.selectPage(teamPage, queryWrapper);
        pageList.getRecords().forEach(sysTeam -> {
            sysTeam.setTag(analyzeTags(sysTeam.getTag(), 1));
            sysTeam.setUsername(sysUserMapper.selectById(sysTeam.getCreatorId()).getUsername());
        });

        return ResultUtils.pageSuccess(pageList);
    }

    @Transactional
    @Override
    public BaseResponse<SysTeam> createTeam(SysTeam sysTeam) {
        // 校验战队名称是否已存在
        LambdaQueryWrapper<SysTeam> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysTeam::getTeamName, sysTeam.getTeamName());
        if (sysTeamMapper.exists(queryWrapper)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "战队名称已存在");
        }
        // 保存战队
        boolean save = sysTeamMapper.insert(sysTeam) > 0;
        if (!save) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "创建战队失败");
        }
        // 保存战队成员
        SysTeamUser sysTeamUser = new SysTeamUser();
        sysTeamUser.setTeamId(sysTeam.getId());
        sysTeamUser.setUserId(sysTeam.getCreatorId());
        sysTeamUser.setJoinTime(new Date());
        sysTeamUser.setJoinType(0);
        sysTeamUser.setRole(1);
        sysTeamUser.setStatus(1);

        sysTeamUserService.save(sysTeamUser);
        return ResultUtils.success(sysTeam);
    }

    public String analyzeTags(String tagsIds, Integer types) {
        if (tagsIds == null || tagsIds.trim().isEmpty()) {
            return "";
        }
        try {
            List<Integer> tagIdList = Arrays.stream(tagsIds.split(",")).map(String::trim).filter(s -> !s.isEmpty()).map(Integer::valueOf).collect(Collectors.toList());

            if (tagIdList.isEmpty()) {
                return "";
            }
            LambdaQueryWrapper<SysTag> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.in(SysTag::getId, tagIdList).eq(SysTag::getTagType, types);
            List<SysTag> sysTags = sysTagMapper.selectList(queryWrapper);

            return sysTags.stream().map(SysTag::getTagName).filter(Objects::nonNull).collect(Collectors.joining(","));
        } catch (NumberFormatException e) {
            return "";
        }
    }
}

